package com.zhouke.certificate.controller;

import com.zhouke.certificate.common.Result;
import com.zhouke.certificate.config.AuthAccess;
import com.zhouke.certificate.entity.User;
import com.zhouke.certificate.service.IUserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

import com.zhouke.certificate.service.ICommentService;
import com.zhouke.certificate.entity.Comment;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周科
 * @since 2022-07-24
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private ICommentService commentService;
    @Resource
    private IUserService userService;
    //新增或更新
    @PostMapping
    public Result save(@RequestBody Comment comment) {  // 返回 Boolean
        return Result.success(commentService.saveOrUpdate(comment));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) { //返回 Boolean
        return Result.success(commentService.removeById(id)); // table.entityPath= user
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){  //返回 Boolean
        return Result.success(commentService.removeByIds(ids));
    }


    //查询所有
    @AuthAccess
    @GetMapping
    public Result findAll() { //返回 List<Comment>
        return Result.success(commentService.list());
    }

    //根据id查询
    @AuthAccess
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) { // 返回 Comment
        return Result.success(commentService.getById(id));
    }

    //查询多级评论
    @AuthAccess
    @GetMapping("/tree/{articleId}")
    public Result findTree(@PathVariable Integer articleId){

        List<Comment> articleComment=commentService.findTree(articleId);//显示文章的所有评论
        //获取所有楼主
        List<Comment> originList=articleComment.stream().filter(comment->comment.getOriginId()==null).collect(Collectors.toList());

        //每楼的所有回复
        for(Comment origin:originList){
            List<Comment> children = articleComment.stream().filter(comment -> origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            //设置回复的用户名
            for(Comment comment:children){
                Comment pComment=commentService.getById(comment.getPid());
                User puser=userService.getById(pComment.getUserId());
                comment.setPName(puser.getRealName());
            }
            origin.setChildren(children);
        }

        return Result.success(originList);
    }
}

